<?php

namespace app\common\job;

use think\Exception;
use think\queue\Job;
use think\facade\Db;
use app\common\traits\ActionRecordTrait;

class CancelOrder
{
    use ActionRecordTrait;
    /**
     * fire是消息队列默认调用的方法
     * @param Job $job 当前的任务对象
     * @param array|mixed $data 发布任务时自定义的数据
    */
    public function fire(Job $job, $data)
    {

        print_r( "==========fire".PHP_EOL );
        $params   = $data['params'];

        //有效消息到达消费者时可能已经不再需要执行了
        if ( !$this->checkJob( $data ) ) {
            $job->delete();
            return;
        }

        //这里预防 非正常情况下重复执行问题
        if( $job->attempts() > 5 ) {
            $job->delete();

            //删除超过执行次数的队列
            $this->deleteAttemptsQueue( $params, $job->attempts() );
            return;
        }

        //执行业务处理
        if ( $this->doJob( $data ) ) {
            $job->delete();//任务执行成功后删除
            print_r( 'dismiss job has been down and deleted'.PHP_EOL );
        } else {
            //检查任务重试次数
            if( $job->attempts() > 2 ) {
                print_r( "==========dismiss job has been retried more that 3 times".PHP_EOL );
                $job->delete();

                //删除超过执行次数的队列
                $this->deleteAttemptsQueue( $params, $job->attempts() );
            }
        }
    }

    /**
     * 消息在到达消费者时可能已经不需要执行了
     * @param array|mixed $data 发布任务时自定义的数据
     * @return boolean 任务执行的结果
     */
    private function checkJob($data)
    {
        print_r( "==========checkJob".PHP_EOL );
        $time     = $data['time'];
        $params   = $data['params'];
        $order_id = $params['order_id'];
        // 订单状态改变，不需要取消支付
        $orderInfo = Db::name('shop_order')->where('id',$order_id)->find();
        if(!in_array($orderInfo['status'],[0,1]) || $orderInfo['is_pay'] == 1)
        {
            return false;
        }

        return true;
    }

    /**
     * 根据消息中的数据进行实际的业务处理
    */
    private function doJob( $data )
    {
        print_r( "==========doJob".PHP_EOL );
        $params   = $data['params'];
        // 实际业务流程处理
        $order_id = $params['order_id'];
        $delay_time = $params['delay_time'];
        try {
            $orderInfo = Db::name('shop_order')->where('id',$order_id)->find();
            $time = time() - $orderInfo['create_time'];
            if(in_array($orderInfo['status'], [0,1]) && !$orderInfo['is_pay'] && $time >= $delay_time)
            {
                $data = [
                    'status' => 6,
                    'update_time' => time(),
                    'cancel_time' => time()
                ];
                $res = Db::name('shop_order')->where('id',$order_id)->update($data);
                if($res)
                {
                    $content = '自动取消超时未支付订单';
                    $arr = [0=>'待审核',1=>'已审核',2=>'已下推',3=>'已发货',4=>'已收货',5=>'已完成',6=>'已作废'];
                    $content .= '，状态：【' . $arr[$orderInfo['status']] . '】修改为【' . $arr[6] . '】';
                    $this->addActionRecord(1,'shop_order_check',$order_id,$content,'shop','order','');
                }
            }
            else{
                return false;
            }
        }catch ( \Exception $e ) {
            return false;
        }

        return true;
    }

    /**
     * 删除超过执行次数的队列
     */
    public function deleteAttemptsQueue( $params, $attempts=1 )
    {
        //日志处理//
        $order_id = $params['order_id'];
        $content = '自动取消超时未支付订单失败,请手动作废订单';
        $this->addActionRecord(1,'shop_order_check',$order_id,$content,'shop','order','');
    }

}